package com.canbot.u05.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.R;
import com.canbot.u05.activity.shoppingGuide.sales.SalesMapPreviewActivity;
import com.canbot.u05.adapter.sales.ItemSelectMapSalesAdapter2;
import com.canbot.u05.bean.JsonResponse;
import com.canbot.u05.bean.sales.ChoosePicBean;
import com.canbot.u05.network.SalesApi;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.widget.LoadingDialogUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 选择图片
 *
 * @author liutao
 */
public class ChoosePicActivity extends BaseActivityNoTitle implements AdapterView.OnItemClickListener {

        private android.widget.TextView tvtitle;

        private android.widget.Button btndelete;

        private android.widget.GridView gvcontent;

        private android.widget.TextView btncancel;

        private android.widget.TextView btnok;

        private android.widget.RelativeLayout activityselectmap;

        private List<ChoosePicBean> choosePicBeen = new ArrayList<>();

        private ItemSelectMapSalesAdapter2 adapter;

        private int index;//当前那个item被选中

        private Dialog dialogLoading;

        //    private String url = "http://"+ IpMsgConst.CHEST_SOCKET_HOST+ ":7755";
        private String picPath;
        private static final int TIMEOUT = 100;//超时时间100s

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_select_map);
                picPath = getIntent().getStringExtra("pic");
                initView();
                adapter = new ItemSelectMapSalesAdapter2(this, choosePicBeen);
                gvcontent.setAdapter(adapter);
                initData();
                initEvent();
                gvcontent.setOnItemClickListener(this);
        }

        private void initEvent() {

        }

        //初始化数据
        private void initData() {
        /*for (int i = 0; i < 20; i++) {
            ChoosePicBean map = new ChoosePicBean(i, R.drawable.low_map_sales, false);
            choosePicBeen.add(map);
            adapter.notifyDataSetChanged();
        }*/
                dialogLoading = LoadingDialogUtils.createLoadingDialog(ChoosePicActivity.this, getResources().getString(R.string.request));
                dialogLoading.show();
                String url = "http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755/";
                Logger.e("t", url);
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl(url)
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(setTimeOut())
                        .build();
                SalesApi salesApi = retrofit.create(SalesApi.class);
                final Call<JsonResponse> pic = salesApi.getPic("/uupic");
                pic.enqueue(new Callback<JsonResponse>() {
                        @Override
                        public void onResponse(Call<JsonResponse> call, Response<JsonResponse> response) {
                                if (response.body() != null) {
                                        final JsonResponse path = response.body();
                                        Logger.e("ChoosePicActivity", response.isSuccessful() + " " + path);
                                        if (path != null) {
//                        JsonResponse jr = JSON.parseObject(response.body(), JsonResponse.class);
                                                if (path.getRc() == -1) {
                                                        return;
                                                }
                                                runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                                if (dialogLoading != null){
                                                                        dialogLoading.setCancelable(true);
                                                                        dialogLoading.dismiss();
                                                                }
                                                                List<String> result = JSON.parseArray(path.getResult().toString(), String.class);
                                                                Logger.e("ChoosePicActivity", "result==" + result.toString());
                                                                for (int i = 0; i < result.size(); i++) {
                                                                        String s = result.get(i);
                                                                        Logger.e("ChoosePicActivity", "编辑图片原图片设置选中picPath" + picPath + "------" + s);

                                                                        if (picPath != null && picPath.equals(s)) {
                                                                                ChoosePicBean map = new ChoosePicBean(s, true);
                                                                                choosePicBeen.add(map);
                                                                                index = i;
                                                                        }
                                                                        else {
                                                                                ChoosePicBean map = new ChoosePicBean(s, false);
                                                                                choosePicBeen.add(map);
                                                                        }
                                                                }
                                                        }

                                                });
                                                adapter.notifyDataSetChanged();
                                        }

                                }
                        }

                        @Override
                        public void onFailure(Call<JsonResponse> call, Throwable t) {
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                dialogLoading.dismiss();
                                                ToastTools.newInstance(ChoosePicActivity.this).showText(getString(R.string.network_error));
                                        }
                                });
                        }
                });


        }

        private void initView() {
                this.activityselectmap = (RelativeLayout) findViewById(R.id.activity_select_map);
                this.btnok = (TextView) findViewById(R.id.btn_ok);
                this.btncancel = (TextView) findViewById(R.id.btn_cancel);
                this.gvcontent = (GridView) findViewById(R.id.gv_content);
                this.btndelete = (Button) findViewById(R.id.btn_delete);
                this.tvtitle = (TextView) findViewById(R.id.tv_title);

        }

        /**
         * 取消选择
         *
         * @param view
         */
        public void cancel(View view) {
                finish();
                overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);
        }

        /**
         * 确定选中图片
         *
         * @param view
         */
        public void ok(View view) {
                ChoosePicBean map = null;
                for (int i = 0; i < choosePicBeen.size(); i++) {
                        if (choosePicBeen.get(i).isChecked() == true) {
                                map = choosePicBeen.get(i);
                        }
                }

                if (map != null && map.getImagePath() != null) {
                        Log.d("ChoosePicActivity", "选中" + map.getImagePath() + "");

                        Intent intent = new Intent();
                        Bundle bundle = new Bundle();
                        bundle.putString("pic", map.getImagePath() + "");
                        intent.putExtra("path", bundle);
                        setResult(RESULT_OK, intent);
                        finish();
                }
                else {
                        ToastTools.newInstance(ChoosePicActivity.this).showText(getString(R.string.please_select_picture));
                }
        }

        /**
         * 返回
         *
         * @param view
         */
        public void delete(View view) {
                finish();
                overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);
        }

        /**
         * gridview的条目点击事件
         *
         * @param adapterView
         * @param view
         * @param i
         * @param l
         */
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Log.d("ChoosePicActivity", "i:" + i);
                index = i;
                ChoosePicBean choosePicBean = choosePicBeen.get(i);
                String imagePath = choosePicBean.getImagePath();
                Intent intent = new Intent(ChoosePicActivity.this, SalesMapPreviewActivity.class);
                intent.putExtra("path", imagePath);
                startActivityForResult(intent, 102);
                Log.d("ChoosePicActivity", "当前预览的图片的路径：-----》" + imagePath);
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                Log.d("ChoosePicActivity", "data:" + data + "requestCode " + requestCode + "requestCode " + requestCode);
                if (requestCode == 102 && resultCode == RESULT_OK && data != null) {
                        boolean ischeck = data.getBooleanExtra("ischeck", false);
                        Log.d("ChoosePicActivity", "判断图片预览的时候是否直接选中图片ischeck:" + ischeck);
                        if (ischeck) {
                                Log.d("ChoosePicActivity", "index:" + index);
                                ChoosePicBean choosePicBean = choosePicBeen.get(index);
                                choosePicBean.setChecked(true);
                                //把其他图片的选中状态置为false
                                for (int i = 0; i < choosePicBeen.size(); i++) {
                                        ChoosePicBean choosePicBean2 = choosePicBeen.get(i);
                                        if (!choosePicBean2.getImagePath().equals(choosePicBean.getImagePath())) {
                                                choosePicBean2.setChecked(false);
                                        }
                                        else {
                                                choosePicBean2.setChecked(true);
                                        }
                                }
                                adapter.notifyDataSetChanged();
                                Log.d("ChoosePicActivity", "修改后的actionMaps:" + choosePicBeen);

                        }
                }
        }
        /**
         * 设置超时
         * @return
         */
        private OkHttpClient setTimeOut(){
                OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .writeTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .readTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .build();
                return client;

        }

        @Override
        protected void onDestroy() {
                super.onDestroy();
                if (dialogLoading != null){
                        dialogLoading.dismiss();
                }
        }
}
